package com.bdqn.interceptor;

import com.bdqn.dto.ApiResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class StaffInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String token = request.getHeader("token");
        System.out.println(token);
        //1、判断前端是否带了请求头token参数
        if (!StringUtils.isEmpty(token)) {

            //2、从redis 读取token的值，获取当前登录用户
            try (Jedis jedis = new Jedis("47.106.226.199", 6429)) {
                jedis.auth("666t01");
                String userName = jedis.get(token);

                //3、验证 token 信息里的userid是否正确  //查数据库 验证用户id正不正确
                if (!StringUtils.isEmpty(userName)) {
                    jedis.setex(token, 60 * 20, userName);
                    return true;//通过拦截器，正常处理Controller方法
                } else {
                    return errorReturnJsonToFont(response, new ApiResult(500, "token已经失效", null));
                }
            }
        } else {
            return errorReturnJsonToFont(response, new ApiResult(500, "请先登录", null));
        }
    }

    public boolean errorReturnJsonToFont(HttpServletResponse response, ApiResult apiResult) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        out.print(mapper.writeValueAsString(apiResult));
        out.flush();
        out.close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("视图处理中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图处理后、处理完成");
    }
}
